package com.wetao.module_homework.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.EventBus.EventBusMessage;
import com.wetao.lib_common.base.BaseListResponse;
import com.wetao.lib_common.base.BaseNestingLazyFragment;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.request.CommitAssistantQuestionsOnlineReq;
import com.wetao.lib_common.bean.request.CommitAssistantQuestionsReq_vo;
import com.wetao.lib_common.bean.request.GetSubjectExamNumberReq;
import com.wetao.lib_common.bean.response.GetSubjectExamNumber;
import com.wetao.lib_common.bean.response.GetSubjectList;
import com.wetao.lib_common.bean.response.StudentExamListInfo;
import com.wetao.lib_common.bean.response.StudentExamQuestion;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.greendao.model.AssistantExamOnline;
import com.wetao.lib_common.greendao.model.AssistantQuestionOnline;
import com.wetao.lib_common.greendao.model.PagePictureOnline;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.GsonUtil;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.MyDividerItemDecoration;
import com.wetao.lib_common.utils.QuestionTypeUtil;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.utils.WrapContentLinearLayoutManager;
import com.wetao.lib_common.utils.oss.OssParams;
import com.wetao.lib_common.utils.oss.UploadOss;
import com.wetao.module_homework.HomeworkLineActivity;
import com.wetao.module_homework.R;
import com.wetao.module_homework.R2;
import com.wetao.module_homework.adapter.HomeworkMain_h_Adapter;
import com.wetao.module_homework.adapter.HomeworkMain_v_Adapter;
import com.wetao.module_homework.contract.HomeworkMainFragmentCon;
import com.wetao.module_homework.presenter.HomeworkMainFragmentPre;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;


public class HomeworkMainFragment extends BaseNestingLazyFragment<HomeworkMainFragmentCon.View, HomeworkMainFragmentPre>
        implements HomeworkMainFragmentCon.View  {

    private static final String ARG_PARAM1 = "param1";
    private OnFragmentInteractionListener mListener;
    private boolean isYes = false; //false：待完成， ture: 已完成

    List<GetSubjectList> mSubjectList;
    List<StudentExamListInfo.Data.RecordsBean> mStudentExamList = new ArrayList<>();;
    @BindView(R2.id.srl_refresh)
    SmartRefreshLayout srl_refresh;
    @BindView(R2.id.rv_h)
    RecyclerView rv_h;
    @BindView(R2.id.rv_v)
    RecyclerView rv_v;
    @BindView(R2.id.iv_no_data)
    ImageView iv_no_data;
    @BindView(R2.id.tv_no_data)
    TextView tv_no_data;
    private HomeworkMain_h_Adapter mHomeworkMain_h_Adapter;
    private HomeworkMain_v_Adapter mHomeworkMain_v_Adapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private MyDividerItemDecoration mDividerItemDecoration;
    private int mCurSubjectPosition = 0;
    private int current = 1;
    private int pages = 1;
    private int size = 10;
    private int total = 1;
    private String studentId;

    private String mExamNumberReqJson;
    private boolean mIsFirstExamNumbReq = true;
    private boolean mIsResumeFirst = true;

    public HomeworkMainFragment() {
    }

    public static HomeworkMainFragment newInstance(boolean param1) {
        HomeworkMainFragment fragment = new HomeworkMainFragment();
        Bundle args = new Bundle();
        args.putBoolean(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.homework_main_fragment;
    }

    @Override
    public HomeworkMainFragmentPre createPresenter() {
        return new HomeworkMainFragmentPre(mContext);
    }

    @Override
    public HomeworkMainFragmentCon.View createView() {
        return this;
    }



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        LogUtils.e("onAttach");
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        LogUtils.e("onDetach");
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onFragmentFirst() {
        super.onFragmentFirst();
    }

    @Override
    public void onFragmentVisble() {
        super.onFragmentVisble();
        if(!mIsFirstExamNumbReq) {
            getSubjectExamNumber();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!mIsResumeFirst) {
            if(!isYes) {
                getSubjectExamNumber();
            }
            getStudentExamList(1);
        }
    }

    @Override
    public void onFragmentInVisible() {
        super.onFragmentInVisible();
    }

    @Override
    public void getSubjectExamNumberResult(BaseListResponse<GetSubjectExamNumber> response) {
        if(response.getData() != null) {
            int position = -1;
            for(GetSubjectExamNumber item : response.getData()) {
                for(int i = 0; i < mSubjectList.size(); i++) {
                    if(item.getSubjectId().intValue() == mSubjectList.get(i).getSubjectId().intValue()) {
                        mSubjectList.get(i).setExamNum(item.getExamNum());
                        if(item.getExamNum().intValue() > 0 && position == -1) {
                            position = i;
                        }
                        break;
                    }
                }
            }
            if(position == -1) {
                position = 0;
            }
            if(mIsFirstExamNumbReq) {
                mCurSubjectPosition = position;
                if(position < mSubjectList.size()) {
                    mHomeworkMain_h_Adapter.setmCurPosition(position);
                    mHomeworkMain_h_Adapter.updateData(mSubjectList);

                    getStudentExamList(1);
                }
            } else {
                mHomeworkMain_h_Adapter.updateData(mSubjectList);
            }

            mIsFirstExamNumbReq = false;
        }
    }

    @Override
    public void getSubjectExamNumberFailed() {

    }

    @Override
    public void studentExamListResult(StudentExamListInfo response, int cur) {
        mIsResumeFirst = false;
        finishSmart(cur);
        if(response.getData() != null) {
            current = cur;
            pages = response.getData().getPages();
            size = response.getData().getSize();
            total = response.getData().getTotal();
            if(!isYes) {
                for (int i = 0; i < response.getData().getRecords().size(); i++) {
                    StudentExamListInfo.Data.RecordsBean item = response.getData().getRecords().get(i);
                    AssistantExamOnline examOnline = DBUtils.getInstance(getContext()).getAssistantExamOnlineByPublishId(item.getExamPublishId(), item.getExamId(), studentId);
                    if (null != examOnline) {
                        item.setAnswerAmount(examOnline.getDealNum());
                    }
                }
            }
            mStudentExamList.addAll(response.getData().getRecords());
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }

            mHomeworkMain_v_Adapter.updateData(mStudentExamList);
            if(mStudentExamList.size() == 0) {
                iv_no_data.setVisibility(View.VISIBLE);
                tv_no_data.setVisibility(View.VISIBLE);
                rv_v.setVisibility(View.GONE);
                if(isYes) {
                    tv_no_data.setText("暂无已完成作答~");
                } else {
                    tv_no_data.setText("暂无待完成作答~");
                }
            } else {
                iv_no_data.setVisibility(View.GONE);
                tv_no_data.setVisibility(View.GONE);
                rv_v.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void studentExamListFailed(int cur) {
        finishSmart(cur);
    }

    @Override
    public void getCommitAnswerResult(BaseResponse response) {
        ToastUtil.initToast("强制提交成功！");

        if(!isYes) {
            getSubjectExamNumber();
        }
        getStudentExamList(1);
    }

    @Override
    public void getCommitAnswerFailed() {
        ToastUtil.initToast("提交失败！");
    }

    @Override
    public void init(View rootView) {
        if (getArguments() != null) {
            isYes = getArguments().getBoolean(ARG_PARAM1);
        }

        initRecyclerView();
        initSmartRefresh();
        String str = SPUtils.getInstance().getString(Constants.GET_SUBJECT_LIST);
        studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        mSubjectList = JsonUtils.fromJsonList(str, new TypeToken<List<GetSubjectList>>() {}.getType());
        if(isYes) {
            if( mSubjectList.size() > 0) {
                mHomeworkMain_h_Adapter.setmCurPosition(0);
                mHomeworkMain_h_Adapter.updateData(mSubjectList);
                getStudentExamList(1);
            }
        } else {
            if(mSubjectList != null && mSubjectList.size() > 0) {
                List<Integer> iList = new ArrayList<>();
                for(GetSubjectList item : mSubjectList) {
                    iList.add(item.getSubjectId());
                }
                GetSubjectExamNumberReq req = new GetSubjectExamNumberReq(iList, isYes?2:1);
                mExamNumberReqJson = JsonUtils.toJson(req);
                getSubjectExamNumber();
            }
        }
    }
    private void getSubjectExamNumber() {
        getPresenter().getSubjectExamNumber(mExamNumberReqJson, false, false);
    }

    //有从activity中eventbus中调用的。
    public void getStudentExamList(int cur) {
        getPresenter().studentExamList(ComUtil.getHashmapByStr(
                new String[]{"itemSubject", "state", "pageNo", "pageSize"},
                new String[]{mSubjectList.get(mCurSubjectPosition).getSubjectId() +"", isYes ? "1" : "0", cur + "", "10"}), false, false, cur);
    }


    private void initSmartRefresh() {
        srl_refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                LogUtils.i("---加载更多");
                if(pages>current){
                    getStudentExamList(current + 1);
                }else {
                    refreshLayout.getLayout().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                        }
                    }, 1000);
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                LogUtils.i("---下拉刷新");
                getStudentExamList(1);
            }
        });
        srl_refresh.setRefreshHeader(new ClassicsHeader(getActivity()));
        srl_refresh.setRefreshFooter(new ClassicsFooter(getActivity()));
    }
    public void resetNoMoreData(){
        if(srl_refresh!=null){
            srl_refresh.resetNoMoreData();//去除没有更多数据状态
        }
    }

    public void finishSmart(int cur) {
        if(cur == 1) {
            resetNoMoreData();
            mStudentExamList.clear();
        }
        if(srl_refresh!=null){
            srl_refresh.getLayout().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(srl_refresh != null) {
                        srl_refresh.finishRefresh();
                        srl_refresh.finishLoadMore();
                    }
                }
            }, 500);
        }
    }

    private void initRecyclerView() {
        mLayoutManager = new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        mHomeworkMain_h_Adapter = new HomeworkMain_h_Adapter(mContext);
        rv_h.setLayoutManager(mLayoutManager);
        mDividerItemDecoration = new MyDividerItemDecoration(getActivity(), LinearLayoutManager.HORIZONTAL, R.drawable.divider_mileage_voice_class);
        //rv_h.addItemDecoration(mDividerItemDecoration);
        rv_h.setItemAnimator( new DefaultItemAnimator());
        rv_h.setAdapter(mHomeworkMain_h_Adapter);
        ((HomeworkMain_h_Adapter)mHomeworkMain_h_Adapter).setOnItemClickListener(new HomeworkMain_h_Adapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                LogUtils.i("onItemClick--" + position);
                mCurSubjectPosition = position;
                if(!mIsFirstExamNumbReq) {
                    getSubjectExamNumber();
                }
                getStudentExamList(1);
            }
        });


        mLayoutManager = new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mHomeworkMain_v_Adapter = new HomeworkMain_v_Adapter(isYes);
        rv_v.setLayoutManager(mLayoutManager);
        mDividerItemDecoration = new MyDividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.divider_mileage_voice_class);
        //rv_v.addItemDecoration(mDividerItemDecoration);
        rv_v.setItemAnimator( new DefaultItemAnimator());
        rv_v.setAdapter(mHomeworkMain_v_Adapter);
        ((HomeworkMain_v_Adapter)mHomeworkMain_v_Adapter).setOnItemClickListener(new HomeworkMain_v_Adapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                LogUtils.i("onItemClick--" + position);
                if(position >= mStudentExamList.size()) {
                    return;
                }
                StudentExamListInfo.Data.RecordsBean item = mStudentExamList.get(position);

                if(!isYes && 3 == item.getState()) {//考试已结束,学生未提交
                    DialogXUtil.customDialogShow("当前作答已超时,\r\n已作答数据将自动提交。", "", "知道了", true, new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {

                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
                    exceptionSubmitCount=0;
                    setQuestionAnswer(item);
                    return;
                }

                if(!isYes && 0== item.getState()) {//考试未开始
                    DialogXUtil.customDialogShow("当前未到作答时间,\r\n请在作答时间内作答。", "", "知道了", true, new DialogXUtil.OnDialogXListen() {
                        @Override
                        public void onListenDialogOk() {

                        }

                        @Override
                        public void onListenDialogCancel() {

                        }

                        @Override
                        public void onListenDialogClose() {

                        }
                    });
                    return;
                }


                ARouter.getInstance().build(isYes ? ConstantArouter.PATH_HOMEWORK_DETAILACTIVITY: ConstantArouter.PATH_HOMEWORK_LINEACTIVITY)
                        .withString("examName",item.getExamName())
                        .withInt("examId",item.getExamId())
                        .withInt("publishId",item.getExamPublishId())
                        .withInt("studentExamId",item.getStudentExamId())
                        .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        .navigation();
                //DialogXUtil.customDialogShow("正在打开考试..."); //会连续闪出两个提示，测试让将这个提示去掉
            }
        });
    }


    public void notifyRefreshAdapterItem(int examId, int publishId, int progress){
        if(isYes) return;

        if(null != mStudentExamList && mStudentExamList.size() > 0) {
            int pos = -1;
            for (int i = 0; i < mStudentExamList.size(); i++) {
                if(publishId == mStudentExamList.get(i).getExamPublishId().intValue()
                        && examId == mStudentExamList.get(i).getExamId().intValue() ) {
                    pos = i;
                    break;
                }
            }
            if(pos > -1) {
                mStudentExamList.get(pos).setAnswerAmount(progress);
                mHomeworkMain_v_Adapter.notifyItemChanged(pos);
            }
        }
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)// sticky =true,可以接收粘性事件。
    public void busStickyMessage(EventBusMessage messageEvent) {
        int action = messageEvent.getAction();
        String msg = messageEvent.getMsg();
        if(action == EventBusMessage.EVENT_BUS_ACTION_ANSWER_PROGRESS){
            if(TextUtils.isEmpty(msg)) return;
            String[] str = msg.split("###");
            notifyRefreshAdapterItem(Integer.parseInt(str[0]), Integer.parseInt(str[1]), Integer.parseInt(str[2]));
        }
    }

    public interface OnFragmentInteractionListener {

    }

    private int exceptionSubmitCount = 0;
    private void setQuestionAnswer(StudentExamListInfo.Data.RecordsBean bean) {
        if(!ComUtil.isNetworkConnected()){
            ToastUtil.initToast(getString(com.wetao.lib_common.R.string.network_disconnect));
            return;
        }

        List<CommitAssistantQuestionsReq_vo> answerList = new ArrayList<>();
        HashMap<String, String> answerMap = null;
        HashMap<Integer,Integer> timerMap = null;
        AssistantExamOnline assistantExam = DBUtils.getInstance(mContext).getAssistantExamOnlineByPublishId(bean.getExamPublishId(), bean.getExamId(), SPUtils.getInstance().getString(Constants.USER_ID_KEY));
        if(null != assistantExam && !TextUtils.isEmpty(assistantExam.getTempAnswer())
                && (answerMap = JsonUtils.fromJson(assistantExam.getTempAnswer(),
                new TypeToken<HashMap<String, String>>() {}.getType())) != null) {
            LogUtils.i("answerMap = " + GsonUtil.GsonString(answerMap));

            if (assistantExam.getTempTimer()!=null){
                timerMap = JsonUtils.fromJson(assistantExam.getTempTimer(),
                        new TypeToken<HashMap<Integer, Integer>>() {}.getType());
            }

            List<String> emptyNetList = null;
            for (Map.Entry<String, String> entry : answerMap.entrySet()){
                String questionInfo = entry.getKey();
                String[] quest = questionInfo.split("###");
                if(QuestionTypeUtil.isSubjectQuestion(Integer.parseInt(quest[1]))
                        && !TextUtils.isEmpty(entry.getValue())){
                    String[] tmp = entry.getValue().split("###");
                    for (int k = 0; k < tmp.length; k++) {
                        PagePictureOnline pagePicture = DBUtils.getInstance(mContext)
                                .getPagePictureOnlineByPictureLocal(tmp[k]);
                        if(null != pagePicture) {
                            if(TextUtils.isEmpty(pagePicture.getPictureUrl())
                                    && new File(pagePicture.getLocalPath()).exists()){
                                if(null == emptyNetList) {
                                    emptyNetList = new ArrayList<>();
                                }
                                emptyNetList.add(pagePicture.getLocalPath());
                            }
                        }
                    }
                }
            }

            //当前有作答图盘不存在上传图片地址,递归上传图片,上传完后再提交
            if(null != emptyNetList && emptyNetList.size() > 0 && exceptionSubmitCount < 3){
                exceptionSubmitCount++;
               // EventBus.getDefault().post(new EventBusMessage(EventBusMessage.EVENT_BUS_ACTION_UPLOAD_ERROR_SUBMIT, JsonUtils.toJson(emptyNetList)));
                uploadSubmit(emptyNetList, bean);
                return;
            }
            exceptionSubmitCount = 0;

            int key = 0;
            for (Map.Entry<String, String> entry : answerMap.entrySet()) {
                String item = entry.getValue();
                if (!TextUtils.isEmpty(item)) {
                    String question = entry.getKey();
                    if(TextUtils.isEmpty(question)) continue;

                    String[] quesInfo = question.split("###");
                    int questionId = Integer.parseInt(quesInfo[0]);
                    int questionType = Integer.parseInt(quesInfo[1]);

                    if(item.contains(".png") || item.contains(".jpg")) {
                        CommitAssistantQuestionsReq_vo answer = new CommitAssistantQuestionsReq_vo();
                        answer.setQuestionId(questionId);
                        answer.setQuestionType(questionType);
                        answer.setAnswerType(2);
                        LogUtils.d("item = " + item);
                        answer.setCommitTime(timerMap!=null?timerMap.get(key):null);
                        String picUrls = getPicUrls(item, emptyNetList);
                        LogUtils.d("picUrls = " + picUrls);
                        /*if (TextUtils.isEmpty(picUrls))
                            return;*/
                        answer.setAnswerContent(picUrls);
                        answerList.add(answer);
                    } else {
                        CommitAssistantQuestionsReq_vo answer = new CommitAssistantQuestionsReq_vo();
                        answer.setQuestionId(questionId);
                        answer.setQuestionType(questionType);
                        answer.setCommitTime(timerMap!=null?timerMap.get(key):null);
                        answer.setAnswerType(1);
                        answer.setAnswerContent(item);
                        answerList.add(answer);
                    }
                }
                key++;
            }
        }

        CommitAssistantQuestionsOnlineReq req = new CommitAssistantQuestionsOnlineReq();
        req.setPublishId(bean.getExamPublishId());
        req.setStudentId(SPUtils.getInstance().getString(Constants.USER_ID_KEY));
        req.setStudentExamId(bean.getStudentExamId());

        req.setQuestionList(answerList);
        req.setFinishTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
        req.setBeginTime(null != assistantExam ? assistantExam.getBeginTime() : req.getFinishTime());

        getPresenter().getCommitAnswer(GsonUtil.GsonString(req), false, "正在提交已作答考试...", false);
    }

    private String getPicUrls(String str, List<String> exceptList) {
        String[] tmp = str.split("###");
        StringBuilder sb = new StringBuilder();

        for (int k = 0; k < tmp.length; k++) {
            if(null != exceptList && exceptList.contains(tmp[k])) continue;

            PagePictureOnline pagePicture = DBUtils.getInstance(mContext)
                    .getPagePictureOnlineByPictureLocal(tmp[k]);
            if (null != pagePicture && !TextUtils.isEmpty(pagePicture.getPictureUrl())) {
                sb.append(pagePicture.getPictureUrl());
                if (k != tmp.length - 1) {
                    sb.append(",");
                }
            }
        }

        return sb.toString();
    }

    private void uploadSubmit(List<String> exceptionPath, StudentExamListInfo.Data.RecordsBean bean){
       //DialogXUtil.waitDialogShow("正在同步作答...");
        upload(exceptionPath, 0, new HomeworkLineActivity.OnListenProcess() {
            @Override
            public void onListenStart() {

            }

            @Override
            public void onListenEnd(String uploadFile, String localFile, List<String> list, int index, HomeworkLineActivity.OnListenProcess onListenProcess) {
                PagePictureOnline pagePictureOnline = DBUtils.getInstance(mContext)
                        .getPagePictureOnlineByPictureLocal(localFile);
                if (null != pagePictureOnline) {
                    LogUtils.i(localFile + " : " + uploadFile);
                    pagePictureOnline.setPictureUrl(uploadFile);
                    DBUtils.getInstance(mContext).updatePagePictureOnline(pagePictureOnline);
                }

                upload(list, index, onListenProcess);
            }

            @Override
            public void onListenError(List<String> list, int index, HomeworkLineActivity.OnListenProcess onListenProcess) {
                upload(list, index, onListenProcess);
            }

            @Override
            public void onListenAllEnd() {
                //DialogXUtil.waitDialogDismiss();
                setQuestionAnswer(bean);
            }
        });
    }

    private synchronized void upload(final List<String> list, final int index, final HomeworkLineActivity.OnListenProcess onListenProcess) {
        LogUtils.i("upload index = " + index + " size = " + list.size());
        if(index >= list.size()){
            if(null != onListenProcess) {
                onListenProcess.onListenAllEnd();
            }
            return;
        }

        LogUtils.i("upload 002");
        final String temp = list.get(index);
        if(TextUtils.isEmpty(temp) || !new File(temp).exists()){
            if(null != onListenProcess) {
                onListenProcess.onListenError(list, index+1, onListenProcess);
            }
            return;
        }

        if(null != onListenProcess) {
            onListenProcess.onListenStart();
        }
        //这里保存的是原始图路径，需要转换成切图路径上传
        String clipPath = temp.substring(0,temp.lastIndexOf(".")) + "clip" + ".png";
        StringBuilder uploadFile = new StringBuilder();
        uploadFile.append(FileUtils.getFileNameNoExtension(clipPath));
        uploadFile.append("_");
        uploadFile.append(new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS").format(System.currentTimeMillis()));
        uploadFile.append(".png");
        LogUtils.i(temp + " : " + uploadFile.toString());
        UploadOss.getInstance().upload2OSS(uploadFile.toString(), clipPath, new UploadOss.OnUploadListener() {
            @Override
            public String uploadSuccess(String uploadFile, String localFile, OssParams ossParams) {
                if(null != onListenProcess) {
                    onListenProcess.onListenEnd(uploadFile, localFile, list, index+1, onListenProcess);
                }
                return null;
            }

            @Override
            public String uploadFail(String uploadFile, String localFile, OssParams ossParams) {
                if(null != onListenProcess) {
                    onListenProcess.onListenError(list, index+1, onListenProcess);
                }
                return null;
            }
        }, null);
    }


}
